import com.qidi.service.ContentService;
import com.qidi.utils.CommonConstant;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * HEU
 * Harbin Engineering University
 *
 * @author QiDi
 * @date 2022/12/15 19:43
 */
@SpringBootTest
public class test1 {
    @Autowired
    RestHighLevelClient restHighLevelClient;


    @Test
    void search(String keyword, int pageNo, int pageSize) throws IOException {

            if (pageNo <= 1) {
                pageNo = 1;
            }

            //条件搜索
            SearchRequest searchRequest = new SearchRequest(CommonConstant.INDEX);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            //分页
            searchSourceBuilder.from(pageNo);
            searchSourceBuilder.size(pageSize);

            //精确查找
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
            searchSourceBuilder.query(termQueryBuilder);
            searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

            //高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("title");
            highlightBuilder.requireFieldMatch(false)//关闭多个高亮显示
                    .preTags("<span style='color:red'>").postTags("</span>");
            searchSourceBuilder.highlighter(highlightBuilder);

            //执行搜索
            searchRequest.source(searchSourceBuilder);
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //解析结果
        SearchHits hits = response.getHits();
        SearchHit[] hits1 = hits.getHits();
        System.out.println(hits);
        System.out.println(hits1);
    }


}

